
'use strict';

const createConfig = require('uni-config-center');
const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const db = uniCloud.database();
const dbcmd = db.command;

const { 
	wxapi,
	utils: wxutils
} = require('use-api');

const utils = require('../utils');

const uniPushs = {
	// 配置对应的管理后台 appid
	'__UNI__C51FBF2': () => {
		return uniCloud.getPushManager({
			appId: '__UNI__C51FBF2'
		});
	}
};


module.exports = {
	// 根据 uid 获取对应的 devices
	async get_devices(uid) {
		const nowdate = Date.now();
		
		let uids = []
		if (typeof uid === 'string') {
			uids.push(uid);
		} else {
			uids = [...uid];
		}
		
		const res = await db.collection('uni-id-device').where({
			user_id: dbcmd.in(uids),
			// token_expired: this.db.command.gte(nowdate),
		}).field({
			device_id: true,
			push_clientid: true,
			unipush_clientid: true,
			context: true
		}).get();
		
		if (res.data && res.data.length) {
			const appids = [...new Set(res.data.map(x => x.context.APPID))];
			const datas = [];
			appids.forEach(appid => {
				datas.push({
					appid,
					cids: res.data.filter(x => x.context.APPID == appid && x.unipush_clientid).map(x => x.unipush_clientid)
				});
			});
			
			return datas;
		}
		
		return [];
	},
	
	// 发送消息
	async send_msg(uid, data) {
		// 获取对应的 devices
		const devices = await this.get_devices(uid);
		const imRes = [];
		for (let i = 0; i < devices.length; i++) {
			let device = devices[i];
			
			console.log('send_msg device', device);
			if (!uniPushs.hasOwnProperty(device.appid) || !(device.cids && device.cids.length)) continue;
			
			const msgData = {
				"push_clientid": device.cids,
				"title": data.title,
				"content": data.content || JSON.stringify(data),
				"payload": {
					"type": "sys-message-notify",
					"data": data
				}
			};
			
			console.log('send_msg msgData', msgData);
			// 发送IM消息
			const imSendRes = await uniPushs[device.appid]().sendMessage(msgData);
			
			imRes.push(imSendRes);
		}
		
		return imRes;
	},
	
	/**
	 * 	101待发货通知
	 */
	async send_msg_101(uid, req) {
		// 发送消息
		const res = await this.send_msg(uid, req);
			
		return res;
	},
	
	// 201退款申请通知
	// 202退货申请通知
	// 203换货申请通知
	async send_msg_aftersale(uid, req) {
		// 发送消息
		const res = await this.send_msg(uid, req);
			
		return res;
	},
	
	
	// 301分销提现通知
	async send_msg_301(uid, req) {
		// 发送消息
		const res = await this.send_msg(uid, req);
			
		return res;
	},
	// 302零钱提现通知
	async send_msg_302(uid, req) {
		// 发送消息
		const res = await this.send_msg(uid, req);
			
		return res;
	},
	
	// 401用户提交反馈
	async send_msg_401(uid, req) {
		// 发送消息
		const res = await this.send_msg(uid, req);
			
		return res;
	}
}
